package com.yzdlb.security.util;

import java.security.Key;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

/***************************************************************************
 * <pre></pre>
 * @ClassName:  DESCoder.java
 * @PackagePath:  com.yzdlb.security.util
 * @Copyright: 北京数字认证股份有限公司 (C) 2016
 * @Description:  
 * @Author: yangzhendong
 * @Date: 2016年6月13日 下午4:21:57
 ***************************************************************************/
public class DESCoder {
    
    public static final String KEY_ALGORITHM = "DES";
    
    
    /**
     * 加密解密算法 / 工作模式 /填充方式
     */
    public static final String CIPHER_ALGORITHM = "DES/ECB/PKCS5Padding";
    
    private static Key toKey(byte[] key) throws Exception{
        DESKeySpec dks = new DESKeySpec(key);
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(KEY_ALGORITHM);
        SecretKey scretKey = keyFactory.generateSecret(dks);
        return scretKey;
    }
    
    /**
      * <p>DES解密</p>
      * @Description: 解密
      * @param data
      * @param key
      * @return
      * @throws Exception
     */
    public static byte[] decrypt(byte[] data,byte[] key) throws Exception{
        Key k = toKey(key);
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, k);
        return cipher.doFinal(data);
        
    }
    
    public static byte[] encrypt(byte[] data,byte[] key) throws Exception{
        Key k = toKey(key);
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, k);
        return cipher.doFinal(data);
    }
    
    public static byte[] initKey() throws Exception{
        KeyGenerator kg = KeyGenerator.getInstance(KEY_ALGORITHM);
        kg.init(56);
        SecretKey secretKey = kg.generateKey();
        return secretKey.getEncoded();
    }
    
}
